home *** CD-ROM | disk | FTP | other *** search
- /* CPROG9.CPP - run it, then read the comments. */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
-
- main()
- {
- int i, x;
-
- randomize();
-
- for(i=0; i < 20; i++) // We'll do what we're going to do 20 times
- {
- x=random(100); // Put a random number (range 0-99) in x
- printf("%2d is %s\n", x, ((x % 2 == 1 ) ? "odd" : "even") );
- }
- }
- /* The printf() line has three components:
- "%2d is %s\n" - The 2 between % and d right-aligns the
- number in a field two chaarcters wide. Single-digit
- numbers therefore format neatly. The %s expects
- a string as the third parameter.
- x - The second parameter goes into %2d in the format
- string ('format string' is the name given to the
- first parameter in printf() )
- ( (x % 2 == 1 ) ? "odd" : "even" )
- Evaluates as the string "odd" or the string "even"
- depending on the result of the test (x % 2 == 1)
- % is the modulo operator. It yields the remainder
- of dividing x by 2. Odd numbers will give 1, evens
- will give 0. The outer pair of brackets shouldn't
- be necessary, but the compiler seems to get
- confused if you don't help it work out which bit
- belongs to what.
- */
-
-